//当前已重连次数，超过上限则不再重连，彻底关闭连接
var curTryNum = 0;
var maxTryNum = 10;


var websocketUploader = function() {
    var websocket_uploader;
    var connect_url;
    var onMessageCallBack;
    var is_active = false; //是否为活动的，若非客户端主动断开，则尝试重连
    var file_name;
    var mediaRecorder = null;

    this.init = function(url, callBackFun) { init(url, callBackFun) };
    this.sendSocketMsg = function(message) { sendSocketMsg(message) };
    this.closeConnect = function() { closeConnect() };
    this.stopRecord = function() { stopRecord() };
    this.setFileName = function(fileName) { setFileName(fileName) };
    this.setStream = function(stream) {
        setStream(stream)
    };
    var stopRecord = function() {
        if (mediaRecorder) {
            mediaRecorder.stop();
        }
    }
    var setStream = function(stream) {

        try {
            if (!!!mediaRecorder) {
                mediaRecorder = new MediaRecorder(stream);
                mediaRecorder.start(5);
                mediaRecorder.onstop = function(e) {
                    if (!e) {
                        console.log('onstop fired exception:' + e.message);
                    }
                    setTimeout(() => {
                        try {
                            closeConnect();
                        } catch (ex) {
                            //不影响其他的操作
                        }
                    }, 500);
                    mediaRecorder = null;
                    // remote_is_end = 0;
                };
                mediaRecorder.ondataavailable = function(e) {
                    // console.log("data available");
                    var reader = new FileReader();
                    reader.addEventListener("loadend", function() {
                        if (reader.result.byteLength > 0) { //加这个判断，是因为有很多数据是空的，这个没有必要发到后台服务器，减轻网络开销，提升性能吧。
                            // sendSocketMsg(buf);
                            //reader.result是一个含有视频数据流的Blob对象
                            var buf = new Uint8Array(reader.result);
                            sendSocketMsg(buf);
                        }
                    });
                    reader.readAsArrayBuffer(e.data);
                }
            }
        } catch (ee) {
            console.log(ee.message);
        }
    }
    var init = function(url, callBackFun) {
        //连接次数加一
        curTryNum = curTryNum + 1;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            websocket_uploader = new WebSocket(url);
            onMessageCallBack = callBackFun;
            is_active = true;
            connect_url = url;
            websocket_uploader.onopen = function(event) {
                onOpenEvent(event);
                startSendHeart(); //开始心跳检测机制
            };
            websocket_uploader.onclose = function(event) {
                onCloseEvent(event);
            };
            websocket_uploader.onmessage = function(message) {
                // console.info(message.data);
                onMessageEvent(message);
            };
            websocket_uploader.onerror = function(event) {
                console.error("连接失败");
            };
            //监听窗口关闭事件，窗口关闭前，主动关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
            window.onbeforeunload = function() {
                websocket_uploader.close();
                is_active = false;
                file_name = null;
            };
        }
    };

    var setFileName = function(fileName) {
        file_name = fileName;
    };
    var onOpenEvent = function(event) {
        //连接成功时将当前已重连次数归零
        curTryNum = 0;
        var json = {};
        if (!!file_name) {
            json.file_name = file_name;
        }
        sendSocketMsg(JSON.stringify(json));
        console.info("连接成功");
    };
    var onCloseEvent = function(event) {
        if (!is_active) { return; }
        //尝试重新连接一次
        if (curTryNum <= maxTryNum) {
            console.log("enter close event :" + file_name);
            console.error("连接关闭，5秒后重新连接……");
            // 5秒后重新连接，实际效果：每5秒重连一次，直到连接成功
            setTimeout(function() {
                init(connect_url);
            }, 5000);
        } else {
            console.error("连接关闭，且已超过最大重连次数，不再重连");
            websocket_uploader.onclose();
        }
    };
    var onMessageEvent = function(message) {
        onMessageCallBack(message);
    };

    var sendSocketMsg = function(message) {
        if (!window.WebSocket) { return; }
        if (websocket_uploader.readyState == WebSocket.OPEN) {
            websocket_uploader.send(message);
        } else {
            console.error("您还未连接上服务器，请刷新页面重试");
        }
    };

    var closeConnect = function() {
        console.log("enter close fun :" + file_name);
        is_active = false;
        file_name = null;
        clearHeart();
        websocket_uploader.close();
    };
    //重置
    var clearHeart = function() {
        /*
        clearTimeout(timeoutObj);
        */
    };
    //开始
    var startSendHeart = function() {
        //暂时屏蔽心跳机制
        /*timeoutObj = setTimeout(function() {
            if (websocket.readyState == 1) {
                websocket.send("heart");
            }
        }, timeout);*/
    };
};


window.onload = function() {};